import React from 'react';
import { observer } from 'mobx-react';
import { View, Text, ScrollView, TextInput, FlatList } from 'react-native';
import { Actions } from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/Feather';
import _ from 'lodash';
import CustomerItem from './customerItem';
import styles from './styles';
import Separtor from '../../../components/separtor';
import { debounce } from '../../../utils';

@observer
class CheckCustomer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      initList: [],
      keyword: ''
    };
  }
  // onSearch = () => {
  //   const { keyword } = this.state;
  //   const kw = _.trim(keyword);
  //   if (kw) {
  //     this.props.store.searchCustomer(keyword).then(list => {
  //       this.setState({
  //         list
  //       });
  //     });
  //   }
  // };
  componentWillReact() {
    if (
      this.props.customers.data.length > 0 &&
      this.state.initList.length < 1
    ) {
      storage.getAllDataForKey('customers').then(initList => {
        this.setState({
          initList
        });
      });
    }
  }
  onChange = keyword =>
    debounce(() => {
      const kw = _.trim(keyword);
      if (kw) {
        this.props.store.searchCustomer(keyword).then(list => {
          this.setState({
            list,
            keyword
          });
        });
      } else {
        this.setState({
          keyword: ''
        });
      }
    }, this)();

  renderItem = ({ item }) => {
    const onPress = () => {
      Actions.editTask({ item });
    };
    return <CustomerItem data={item} onPress={onPress} />;
  };
  render() {
    if (this.props.customers.data < 1) {
      return null;
    }
    return (
      <View style={styles.wrap}>
        <View style={styles.searchBar}>
          <Icon
            name="search"
            size={24}
            color="#069"
            style={styles.searchIcon}
          />
          <TextInput
            returnKeyType="done"
            onChangeText={this.onChange}
            placeholder="请输入客户的姓名或者手机号查询"
            style={styles.textInput}
          />
        </View>
        <ScrollView style={styles.result}>
          <FlatList
            ListHeaderComponent={
              this.state.keyword ? (
                <Text>
                  关键字：{this.state.keyword} 查询出 {this.state.list.length}个结果
                </Text>
              ) : null
            }
            data={
              this.state.keyword ? this.state.list : this.state.initList || []
            }
            renderItem={this.renderItem}
            keyExtractor={item => item.customerId.toString()}
            ItemSeparatorComponent={Separtor}
            ListEmptyComponent={<Text>没有结果</Text>}
          />
        </ScrollView>
      </View>
    );
  }
}

export default CheckCustomer;
